package com.hzit.order.controller;

import com.alipay.api.AlipayApiException;
import com.hzit.cart.api.domain.Address;
import com.hzit.cart.api.domain.Order;
import com.hzit.cart.api.domain.PayLog;
import com.hzit.cart.api.model.ItemVo;
import com.hzit.order.interceptor.LoginInterceptor;
import com.hzit.order.service.AddressService;
import com.hzit.order.service.OrderService;

import com.hzit.order.service.PayService;
import com.hzit.order.vo.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Controller
@RequestMapping
public class OrderController {

	@Autowired
	private AddressService addressService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private PayService payService;

	//1. 订单的欢迎页面
	@GetMapping({"/","/getOrderInfo.html"})
	public String index(Model model){
		//1.1 查询得到当前登录用户地址列表
		List<Address> addressList = addressService.getAddressList();
		//1.2 得到被选择的购物车的购物项列表
		Map<String,List<ItemVo>> cartMap = orderService.findCartInfo();
		//1.3 将查询得到地址列表信息及购物车信息放到model中
		model.addAttribute("addressList",addressList);
		model.addAttribute("cartMap",cartMap);

		return "getOrderInfo";
	}

	//2. 保存订单
	@PostMapping("/order/add")
	public String saveOrder(OrderVo order, RedirectAttributes attributes) throws ExecutionException, InterruptedException {
		//2.1 得到登录用户名
		String login = LoginInterceptor.threadLocal.get().getLogin();
		//2.2 保存订单及支付日志
		orderService.saveOrder(order,login);
		//2.3 从redis中得到支付日志
		PayLog payLog = orderService.getPayLogFromRedis(login);
		attributes.addAttribute("outTradeNo",payLog.getOutTradeNo());
		attributes.addAttribute("money",payLog.getTotalFee());

		return "redirect:http://order.hzit.com/order/pay.html";
	}

	@GetMapping("/order/pay.html")
	public String pay(){
		return "pay";
	}
	//3. 展示支付页面
	@GetMapping("/order/pay")
	@ResponseBody
	public String orderPay(String outTradeNo,Long money) throws AlipayApiException {
		String result = payService.createPayPage(outTradeNo,money);
		// System.out.println("result = " + result);
		return result;
	}

	//4. 同步通知
	@GetMapping("/order/list")
	public String orderList(Model model){
		List<Order> orders = orderService.getOrderList();
		model.addAttribute("orders",orders);
		return "list";
	}



}
